var CanvasRotater = Class.create({
    initialize : function() {
        this.canvas = $('canvas');
        this.loggedInImage = $('logged_in');
        this.rotation = 0;
        this.canvasContext = this.canvas.getContext('2d');
        this.animationFrames = 36;
        this.animationSpeed = 10;
        this.animationLength = 300;
    },
    ease : function(x) {
        return (1-Math.cos(x*Math.PI))/2;
    },
    setIcon : function(img)
    {
        this.loggedInImage = img;
        this.drawIconAtRotation();
    },
    drawIconAtRotation : function () {
        var w = this.canvas.width;
        var h = this.canvas.height;
        this.canvasContext.save();
        this.canvasContext.clearRect(0, 0,  this.canvas.width,  this.canvas.height);
        this.canvasContext.translate(
            Math.ceil(w/2),
            Math.ceil(h/2));
        this.canvasContext.rotate(2 * Math.PI * this.ease(this.rotation));
        this.canvasContext.drawImage(this.loggedInImage,
            - Math.ceil(w/2),
            - Math.ceil(h/2));
        this.canvasContext.restore();

        chrome.browserAction.setIcon({
            imageData: this.canvasContext.getImageData(0, 0, w, h)
        });
    },
    animateFlip : function(text)
    {
        this.lastTime = new Date();
        setTimeout(this.animateFlipInterval.bind(this, text), this.animationSpeed);
    },

    animateFlipInterval : function(text) {
        this.rotation += (new Date() - this.lastTime) / this.animationLength;
        this.lastTime = new Date();
        this.drawIconAtRotation();

        if (this.rotation <= 1) {
            setTimeout(this.animateFlip.bind(this), this.animationSpeed);
        } else {
            this.rotation = 0;
            this.drawIconAtRotation();
            if(text)
            {
                chrome.browserAction.setBadgeText({text: text});
                chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
            }
        }
    }
});
